import { reactive, computed, toRefs } from 'vue';
import { getArea } from '@/api/merchant';
import { Pagination, PaginationQuery } from '@/types/table';
import { TableState, CheckAble } from '@/types/table';

const tableQuery: PaginationQuery = reactive({
    page: 0,
    size: 9,
    sort: 'id,desc',
    parentAreaCodeIsNull: true,
});

// 角色信息
const state: TableState & CheckAble = reactive({
    dataSource: [],
    selectedRow: {},
    selectedRowKeys: [],
    visible: false,
    loading: false,
    pagination: {
        total: 0,
        current: computed(() => tableQuery.page + 1),
    },
});

// 获取table数据
const getAreaData = async (tableQuery: PaginationQuery) => {
    state.loading = true;
    const { content, totalElements } = await getArea(tableQuery);
    state.loading = false;
    state.dataSource = content.map((item) => {
        return {
            ...item,
            children: [],
        };
    });

    state.pagination.total = totalElements;
};
// 设置table row key
const setRowKey = (record: { [x: string]: any }) => record.id;

// 页码改变
const handleTableChange = (pagination: Pagination) => {
    const { current } = pagination;
    tableQuery.page = current - 1;
    getAreaData(tableQuery);
};

// 显示新增弹窗
const handleAddArea = () => {
    state.selectedRow = {};
    state.visible = true;
};

const handleEditArea = (row: { [x: string]: any }) => {
    state.selectedRow = row;
    state.visible = true;
};

// 取消弹窗
const handleCancle = () => {
    state.visible = false;
};

// 展开行
const handleExpandRow = async (expanded: boolean, record: NormalObj) => {
    console.log(record);
    if (expanded && !record.children.length) {
        const { areaCode } = record;
        const params = {
            parentAreaCode: areaCode,
        };
        const { content } = await getArea(params);
        record.children = content.map((item) => {
            return {
                ...item,
                children: item.subCount ? [] : null,
            };
        });
    }
};

export default {
    handleExpandRow,
    tableQuery,
    handleTableChange,
    handleAddArea,
    handleEditArea,
    getAreaData,
    setRowKey,
    ...toRefs(state),
    handleCancle,
};
